package controller;
import view.*;

import java.io.*;

import javax.swing.JOptionPane;


/**
 * PacShell class serves to initialise a test level, and
 * all resources needed to run an instance of turn-based
 * pacman
 * 
 * @author Alexander Craig
 */
public class PacShell {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		// Copy default levels from the jar file to the file system if it does not exist
		File levelDir = new File("levels");
		if(!levelDir.exists())
			levelDir.mkdir();

		copyFromJar("levels/std.olp");
		copyFromJar("levels/std_1.ots");
		copyFromJar("levels/std_2.ots");
		copyFromJar("levels/std_3.ots");
		copyFromJar("levels/std_4.ots");
		copyFromJar("levels/std_5.ots");
		copyFromJar("levels/std_6.ots");

		// Start the main application
		new PacFrame();
	}
	
	/**
	 * Copies game resources from the jar file to the file system
	 * @param path	the path to the resource to be copied.
	 * @throws IOException
	 */
	public static void copyFromJar(String path) throws IOException {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
			file.createNewFile();
		}
		
		InputStream fis = PacShell.class.getResourceAsStream(path);
	    FileOutputStream fos = new FileOutputStream(file);
		try {
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = fis.read(buf)) != -1) {
				fos.write(buf, 0, i);
			}
		} 
		catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Unable to copy game resources to file system, check that levels directory exists."
					, "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}
		finally {
			if (fis != null) fis.close();
			if (fos != null) fos.close();
		}
			
	}

}
